<?php
namespace App\Blocks;

use App\Models\EatEveryDay;
use App\Models\EatEveryDayPrize;
use App\Models\AdminUsers;
use App\Models\Users;
use DB;
class Activity
{

    public function eatEveryDayPrize($uid, $data, $redeemCode){
        try{
            $prize = [
                'uid' => $uid,
                'img_url' => $data->img_url,
                'show_title' => $data->show_title,
                'name' => $data->name,
                'producing_area' => $data->producing_area,
                'unit' => $data->unit,
                'grade' => $data->grade,
                'redeem_code' => $redeemCode
            ];

            $prizeModel = new EatEveryDayPrize();
            $eatEveryDayModel = new EatEveryDay();

            //规定什么时间开始
            if(date('H') < \Config::get('app.eat_every_day_start_hour')){
                return -2;
            }
            //每天只能抽一次
            $date = date('Y-m-d', time());
            if(DB::table($prizeModel->getTable())
                ->where('uid', $uid)
                ->where('created_at', '>', $date)
                ->count() > 0
            ){
                return -1;
            }

            if(DB::table($prizeModel->getTable())->insert($prize) === false){
                return false;
            }
            if(DB::table($eatEveryDayModel->getTable())
                    ->where('id', $data->id)
                    ->where('stock_num', '>', 0)
                    ->update([
                        'stock_num' => DB::raw('stock_num - 1')
            ]) === false){
                DB::rollBack();
                return false;
            }
            DB::commit();
            return true;
        }catch (\Exception $exception){
            DB::rollBack();
            \Log::error($exception);
            return false;
        }
    }

    //中奖列表
    public function eatEveryDayPrizeList($search = [], $page = 0, $length = 20){
        $prizeModel = new EatEveryDayPrize();
        $userModel = new Users();

        $sql = DB::table($prizeModel->getTable() . ' as p')
            ->select(
                'p.*',
                'u.nick_name'
            )
            ->leftJoin($userModel->getTable() . ' as u', 'p.uid', '=', 'u.id');

        if(isset($search['search'])){
            $sql->where('u.nick_name', 'like', "%".$search['search']."%");
        }

        if(isset($search['mobile'])){
            $sql->where('u.mobile', $search['mobile']);
        }

        $list = $sql->skip(($page - 1)*$length)->take($length)
            ->orderBy('p.created_at', 'desc')
            ->get();

        return $list;
    }
}